import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/city_response_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/user_select_sort_save_response_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';

import '../update_task_view_model.dart';

class PersonalCityWidget extends StatefulWidget {
  final String cityType;
  final FaceUserInfoBean infoBean;

  const PersonalCityWidget(
      {Key key, this.cityType = "04", this.infoBean})
      : super(key: key);

  @override
  _PersonalCityWidgetState createState() =>
      _PersonalCityWidgetState();

  ///跳转方法
  static Future<EditTextAndValue> navigatorPush(
      BuildContext context, FaceUserInfoBean infoBean) {
    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      PersonalCityWidget(
        infoBean: infoBean,
      ),
    );
  }
}

class _PersonalCityWidgetState
    extends BaseState<PersonalCityWidget> {
  bool isLightUp = false;
  String mCityText;

  String selectedId;

  String roleId = UserRepository.getInstance().userData.comUser.roleid;

  CommonListPageWidgetState<CityListItemBean, CityResponseBean>
  _mState;

  void setCommonListState(
      CommonListPageWidgetState<CityListItemBean, CityResponseBean>
      state) {
    _mState = state;
  }

  UpdateTaskViewModel viewModel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.infoBean?.city!=null && widget.infoBean?.city!=""){
      selectedId = widget.infoBean?.city;
    }
    viewModel = UpdateTaskViewModel(this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      // resizeToAvoidBottomPadding: false,
      backgroundColor: Color(0xFF191E31),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            _toTopBarWidget(),
            // if (roleId == "99")
            //   _searchCityWidget(),
            //下划线
            // if (roleId == "99")
            //   Container(
            //     height: 1,
            //     padding: const EdgeInsets.only(
            //       left: 21,
            //     ),
            //     child: Divider(
            //       height: 1.0,
            //       indent: 0.0,
            //       color: Color(0xFF303546),
            //     ),
            //   ),
            // SizedBox(
            //   height: 10,
            // ),
            Expanded(
              child: _toCustomListWidget(),
            ),
          ],
        ),
      ),
    );
  }

  //封装的列表
  Widget _toCustomListWidget() {
    return CommonListPageWidget<CityListItemBean, CityResponseBean>(
      enablePullUp: false,
      enablePullDown: false,
      queryMapFunc: (int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "name": "",
        "type": widget.cityType,
      },
      parseDataFunc: (VgHttpResponse resp) {
        CityResponseBean bean =
        CityResponseBean.fromMap(resp?.data);
        return bean;
      },
      itemBuilder:
          (BuildContext context, int index, CityListItemBean itemBean) {
        return _toListItemWidget(context, index, itemBean);
      },
      //分割器构造器
      separatorBuilder: (context, int index, _) {
        return Container(
          height: 0.5,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          padding: const EdgeInsets.only(left: 15),
          child: Container(
            color: Color(0xFF303546),
          ),
        );
        // return divider;
      },
      netUrl:ServerApi.BASE_URL + "app/appChooseInfo",
      httpType: VgHttpType.post,
      stateFunc: (CommonListPageWidgetState<CityListItemBean, CityResponseBean>
      state) {
        _mState = state;
      },
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, CityListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        //判断字体是否选中
        selectedId = itemBean.id;
        setState(() {});
        //收键盘方法
        // FocusScope.of(context).requestFocus(FocusNode());
        _saveAddCityName();
      },
      child: Container(
        color: Color(0xFF21263C),
        height: 50,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Text(
          itemBean?.name ?? "",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: itemBean.id != selectedId
                ? Color(0xFFD0E0F7)
                : Color(0xFF1890FF),
            fontSize: 14,
          ),
        ),
      ),
    );
  }

  Widget _searchCityWidget() {
    return Container(
      height: 50,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        hintText: "请输入城市名称",
        onChanged: (String cityText) {
          mCityText = cityText;
          if (cityText == null ||
              cityText == "" ||
              cityText.trim().isEmpty)
            isLightUp = false;
          else
            isLightUp = true;
          setState(() {});
        },
        onSubmitted: (String cityText) {
          mCityText = cityText;
          if (cityText == null ||
              cityText == "" ||
              cityText.trim().isEmpty)
            isLightUp = false;
          else
            isLightUp = true;
          setState(() {});
        },
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "城市",
      rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    if (roleId == "99")
      return Container(
        child: CommonFixedHeightConfirmButtonWidget(
          isAlive: isLightUp,
          width: 48,
          height: 24,
          unSelectBgColor:
          ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
          selectedBgColor:
          ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          unSelectTextStyle: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              fontWeight: FontWeight.w600),
          selectedTextStyle: TextStyle(
              color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
          text: "确定",
          onTap: () {
            //提交按钮
            if (isLightUp) {
              _saveAddCityName();
              // _httpSave();
            }
          },
        ),
      );
  }

  void _httpSave() {
    if (mCityText == null || mCityText.isEmpty) {
      VgToastUtils.toast(context, "请输入城市名称");
      return;
    }
    List<CityListItemBean> cityList = _mState?.data;
    if (cityList == null || cityList.isEmpty) {
      // _saveCityNameHttp();
      return;
    }
    for (CityListItemBean item in cityList) {
      if (item?.name == mCityText) {
        _pop(item);
        return;
      }
    }
    // _saveCityNameHttp();
  }

  ///返回部门选中值
  void _pop(CityListItemBean itemBean) {
    if (itemBean == null) {
      return;
    }
    RouterUtils.pop(context,
        result: EditTextAndValue(value: itemBean.id, editText: itemBean.name));
  }

  ///保存接口
  void _saveCityNameHttp() {
    if (mCityText == null || mCityText.isEmpty) {
      VgToastUtils.toast(context, "城市名称不能为空");
      return;
    }
    VgHudUtils.show(context, "保存中");
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddChooseInfo",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "name": mCityText?.trim() ?? "",
          "type": widget.cityType,
        },
        callback: BaseCallback(onSuccess: (dynamic val) {
          VgHudUtils.hide(context);
          if (val == null) {
            return;
          }
          UserSelectSortSaveResponseBean successBean =
          UserSelectSortSaveResponseBean.fromMap(val);
          if (successBean == null ||
              successBean.data == null ||
              successBean.data.isEmpty) {
            VgToastUtils.toast(context, "城市添加返回值错误");
            return;
          }
          CityListItemBean cityListItemBean =
          new CityListItemBean();

          successBean.data.forEach((element) {
            if (element?.name != null &&
                element?.name != "" &&
                element?.name == mCityText) {
              cityListItemBean.id = element.id;
            }
          });
          cityListItemBean.name = mCityText;
          _saveAddCityName();
          setState(() { });
          _pop(cityListItemBean);
        }, onError: (String msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }


  void _saveAddCityName(){
    VgToolUtils.removeAllFocus(context);
    viewModel?.batchAppUpdateChooseInfo(
        context, widget?.infoBean?.fuid, selectedId, "", "", "", "");
    VgToastUtils.toast(context, "设置成功");
  }
}
